import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_tv_widgets/theme/kq_theme_manager.dart';
import '../../resources/kq_theme_colors.dart';
import '../../resources/l10n/kq_intl.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../divider/kq_divider.dart';
import '../searchBar/kq_search_bar.dart';
import 'pull_down_menu_controller.dart';

// ignore: must_be_immutable
class PullDownMenuList extends StatefulWidget {
  /// 控制器
  PullDownMenuController controller;

  /// 是否是自定义组件，如果不是则会调用回调menuDataRender，否则会调用回调menuWidgetRender
  bool Function(int menuIndex) isShowCustomWidget;

  ///返回下拉菜单menuIndex对应的数据
  List<dynamic>? Function(int menuIndex)? menuDataRender;

  /// 非自定义需实现的方法
  /// 下拉菜单每一项绘制器，返回要显示的文本内容
  final String Function(int menuIndex, dynamic item)? menuItemRender;

  ///返回下拉菜单menuIndex对应的widget
  Widget? Function(int menuIndex, PullDownMenuController menuController)?
      menuCustomWidgetRender;

  ///返回菜单header对应menuIndex下拉菜单对应的高度，默认最大458
  double? Function(int menuIndex)? menuWidgetHeight;

  /// 选中菜单回调
  final Function(
          dynamic item, int menuIndex, PullDownMenuController menuController)?
      pullDownCallback;

  ///比较两个是否相同，相同选中
  final bool Function(dynamic item, dynamic compareItem)? isDataSame;

  ///是否显示排序数据，根据位置menuIndex来判断是否要显示排序号码
  final bool Function(int menuIndex)? isShowSortRender;

  ///返回搜索结果,两个参数：1.menu位置；2.搜索的内容
  final List<dynamic>? Function(int menuIndex, String searchContent)?
      searchResultCallback;

  /// 是否时时搜索
  final bool Function(int menuIndex)? aliveTimeSearch;

  ///动画时间
  final int animationMilliseconds;

  ///蒙版颜色
  Color maskColor;

  ///是否使用Overlay
  final bool isUseOverlay;

  ///menu位置是否固定，默认是true
  final bool isFixure;

  /// 点击空白区域回调
  final void Function(int menuIndex, PullDownMenuController menuController)?
      dismiss;

  PullDownMenuList({
    Key? key,
    required this.controller,
    required this.isShowCustomWidget,
    this.menuItemRender,
    this.menuCustomWidgetRender,
    this.menuDataRender,
    this.menuWidgetHeight,
    this.isDataSame,
    this.isShowSortRender,
    this.animationMilliseconds = 150,
    this.maskColor = const Color.fromRGBO(0, 0, 0, 0.3),
    this.pullDownCallback,
    this.searchResultCallback,
    this.aliveTimeSearch,
    this.isUseOverlay = false,
    this.isFixure = true,
    this.dismiss,
  }) : super(key: key);

  @override
  State<PullDownMenuList> createState() => _PullDownMenuListState();
}

class _PullDownMenuListState extends State<PullDownMenuList>
    with SingleTickerProviderStateMixin {
  bool _isShowDropDownItemWidget = false;
  bool _isShowMask = false;
  bool _isControllerDisposed = false;
  Animation<double>? _animation;
  AnimationController? _controller;

  final ScrollController _scrollController = ScrollController();

  // late double _maskColorOpacity;

  double? _dropDownHeight;

  int _currentMenuIndex = 0;

  final Map<int, List<dynamic>> _aliveSearch = {};
  String? _aliveSearchContent;

  @override
  void initState() {
    super.initState();
    _isControllerDisposed = false;
    widget.controller.addListener(_onController);
    _controller = AnimationController(
        duration: Duration(milliseconds: widget.animationMilliseconds),
        vsync: this);
  }

  _onController() {
    // setState(() {});
    bool isReload = widget.controller.isReloadMenu;
    if (isReload) {
      // 为了让外部去刷新菜单
      if (widget.controller.isLayout) {
        if (_isCustomWidget()) {
          renderDropDownCustomWidget();

          // if (!mounted) {
          //   return;
          // }
          // Future.delayed(const Duration(microseconds: 100), () {
          //   setState(() {});
          //   widget.controller.isLayout = false;
          //   widget.controller.isReloadMenu = false;
          // });
          // return;
        }
      }
      if (!mounted) {
        return;
      }
      setState(() {});
      widget.controller.isLayout = false;
      widget.controller.isReloadMenu = false;
    } else {
      if (_isCustomWidget()) {
        renderDropDownCustomWidget();
      } else {
        renderDropDownWidget();
      }
    }
  }

  bool _isCustomWidget() {
    if (Get.isRegistered<PullDownMenuController>()) {
      return widget.isShowCustomWidget(widget.controller.menuIndex);
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    _controller!.duration =
        Duration(milliseconds: widget.animationMilliseconds);
    return _buildDropDownWidget();
  }

  @override
  dispose() {
    _animation?.removeListener(_animationListener);
    _animation?.removeStatusListener(_animationStatusListener);
    // Get.find<PullDownMenuController>().removeListener(_onController);
    _controller?.dispose();
    _isControllerDisposed = true;
    super.dispose();
  }

  //获取数据源
  List<dynamic>? getMenuData() {
    List<dynamic>? list = [];
    if (_aliveSearch[_currentMenuIndex] != null &&
        _aliveSearch[_currentMenuIndex]!.isNotEmpty) {
      list = _aliveSearch[_currentMenuIndex];
    } else {
      if (widget.menuDataRender != null) {
        list = widget.menuDataRender!(_currentMenuIndex);
      }
    }
    return list;
  }

  //默认样式Widget
  renderDropDownWidget() {
    if (!Get.isRegistered<PullDownMenuController>()) {
      return;
    }
    _currentMenuIndex = widget.controller.menuIndex;
    _isShowDropDownItemWidget = !_isShowDropDownItemWidget;

    if (!_isShowMask) {
      _isShowMask = true;
    }

    List<dynamic>? list = getMenuData();

    _dropDownHeight = 458.r;
    if (widget.menuWidgetHeight != null) {
      double? menuH = widget.menuWidgetHeight!(_currentMenuIndex);
      if (menuH == null) {
        if (list != null && list.isNotEmpty) {
          if (list.length * 64.r < 458.r) {
            _dropDownHeight = list.length * 64.r;
          }
        }
      } else if (menuH > 0) {
        _dropDownHeight = menuH;
      }
    } else if (list != null && list.isNotEmpty) {
      if (list.length * 64.r < 458.r) {
        _dropDownHeight = list.length * 64.r;
      }
    }

    _animation?.removeListener(_animationListener);
    _animation?.removeStatusListener(_animationStatusListener);
    _animation = Tween(begin: 0.0, end: _dropDownHeight).animate(_controller!)
      ..addListener(_animationListener)
      ..addStatusListener(_animationStatusListener);
    if (_isControllerDisposed) return;

    if (widget.controller.isShow) {
      _controller!.forward();
    } else if (widget.controller.isShowHideAnimation) {
      _controller!.reverse();
    } else {
      _controller!.value = 0;
    }
  }

  //自定义Widget
  renderDropDownCustomWidget() {
    _currentMenuIndex = widget.controller.menuIndex;

    _isShowDropDownItemWidget = !_isShowDropDownItemWidget;
    // if (widget.dropdownMenuChanging != null) {
    //   widget.dropdownMenuChanging!(
    //       _isShowDropDownItemWidget, _currentMenuIndex);
    // }
    if (!_isShowMask) {
      _isShowMask = true;
    }

    _dropDownHeight = 458.r;
    if (widget.menuWidgetHeight != null) {
      List<dynamic>? list = getMenuData();
      if (widget.menuWidgetHeight!(_currentMenuIndex) == null) {
        if (list != null && list.isNotEmpty) {
          if (list.length * 64.r < 458.r) {
            _dropDownHeight = list.length * 64.r;
          }
        }
      } else {
        _dropDownHeight = widget.menuWidgetHeight!(_currentMenuIndex);
      }
    }
    _animation?.removeListener(_animationListener);
    _animation?.removeStatusListener(_animationStatusListener);
    _animation = Tween(begin: 0.0, end: _dropDownHeight).animate(_controller!)
      ..addListener(_animationListener)
      ..addStatusListener(_animationStatusListener);

    if (_isControllerDisposed) return;
    if (widget.controller.isShow) {
      _controller!.forward();
    } else if (widget.controller.isShowHideAnimation) {
      _controller!.reverse();
    } else {
      _controller!.value = 0;
    }
  }

  void _animationStatusListener(AnimationStatus status) {
    switch (status) {
      case AnimationStatus.dismissed:
        _isShowMask = false;
        // if (widget.dropdownMenuChanged != null) {
        //   widget.dropdownMenuChanged!(false, _currentMenuIndex);
        // }
        break;
      case AnimationStatus.forward:
        break;
      case AnimationStatus.reverse:
        break;
      case AnimationStatus.completed:
        // if (widget.dropdownMenuChanged != null) {
        //   widget.dropdownMenuChanged!(true, _currentMenuIndex);
        // }
        break;
    }
  }

  void _animationListener() {
    // var heightScale = _animation!.value / _dropDownHeight!;
    // _maskColorOpacity = widget.maskColor.opacity * heightScale;
//    print('$_maskColorOpacity');
    //这行如果不写，没有动画效果
    setState(() {});
  }

  Widget _mask() {
    if (_isShowMask) {
      double menuTop = widget.controller.dropDownMenuTop ?? 0;
      double menuHeight = _animation == null ? 0 : _animation!.value;
      //如果下拉是固定位置的，那么底部蒙版的高度必须剪去菜单的高度，非固定则不减
      double maskHeight = MediaQuery.of(context).size.height -
          menuTop -
          (widget.isFixure ? menuHeight : 0);
      return GestureDetector(
        onTap: () {
          if (widget.isUseOverlay) {
            widget.controller.resetPullDownState();
          } else {
            widget.controller.hide();
          }
          widget.dismiss?.call(widget.controller.menuIndex, widget.controller);
        },
        child: Container(
          margin: EdgeInsets.only(
              top: widget.isFixure ? 0 : menuTop, left: 0, right: 0),
          width: widget.controller.menuWidth,
          height: maskHeight,
          color: widget.maskColor,
        ),
      );
    } else {
      return Container(
        height: 0,
      );
    }
  }

  void _dropListViewTop() {
    /// 是否需要滚动到顶点
    if (widget.controller.isChangeIndex) {
      _scrollController.animateTo(0,
          duration: const Duration(microseconds: 10), curve: Curves.ease);
    }
  }

  Widget _buildDropDownWidget() {
    _dropListViewTop();

    int menuIndex = widget.controller.menuIndex;

    var topMaskHeight = 0.0;
    double dropDownMenuTop = widget.controller.dropDownMenuTop ?? 0;
    if (!widget.isFixure) {
      MediaQueryData mediaQuery = MediaQuery.of(context);
      topMaskHeight = mediaQuery.size.height - dropDownMenuTop;
    }
    if (_isCustomWidget()) {
      //自定义
      return Positioned(
          top: widget.controller.dropDownMenuTop,
          left: widget.controller.leftX,
          right: widget.controller.rightX,
          child: Column(
            children: <Widget>[
              widget.menuCustomWidgetRender!(
                          _currentMenuIndex, widget.controller) !=
                      null
                  ? Container(
                      color: KqThemeColors.bgDefault,
                      width: double.infinity,
                      // height: _animation == null ? 0 : _animation!.value,
                      child: widget.menuCustomWidgetRender!(
                          _currentMenuIndex, widget.controller),
                    )
                  : Container(),
              widget.menuCustomWidgetRender!(
                          _currentMenuIndex, widget.controller) !=
                      null
                  ? _mask()
                  : Container(),
            ],
          ));
    } else {
      List<dynamic>? list = getMenuData();

      if (_animation == null) {
        setState(() {});
      }
      return widget.isFixure
          ? Positioned(
              top: dropDownMenuTop,
              left: widget.controller.leftX,
              right: widget.controller.rightX,
              child: Column(
                children: <Widget>[
                  renderSearchBar(menuIndex),
                  renderLine(menuIndex),
                  Container(
                    color: KqThemeColors.bgDefault,
                    width: double.infinity,
                    height: _animation == null ? 0 : _animation!.value,
                    child: renderbuildConditionListWidget(list),
                  ),
                  _mask(),
                ],
              ))
          : Stack(
              clipBehavior: Clip.none,
              children: [
                Positioned(
                  top: 0,
                  right: widget.controller.leftX,
                  left: widget.controller.rightX,
                  bottom: topMaskHeight,
                  child: GestureDetector(
                    onTap: () {
                      if (widget.isUseOverlay) {
                        widget.controller.resetPullDownState();
                      } else {
                        widget.controller.hide();
                      }
                    },
                    child: Container(
                      color: Colors.transparent,
                      width: double.infinity,
                    ),
                  ),
                ),
                _mask(),
                Container(
                  margin: EdgeInsets.only(top: dropDownMenuTop),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      renderSearchBar(menuIndex),
                      renderLine(menuIndex),
                      Container(
                        color: KqThemeColors.bgDefault,
                        width: widget.controller.menuWidth,
                        height: _animation == null ? 0 : _animation!.value,
                        child: renderbuildConditionListWidget(list),
                      ),
                    ],
                  ),
                ),
              ],
            );
    }
  }

  //搜索框
  Widget renderSearchBar(int menuIndex) {
    if (widget.menuDataRender != null) {
      List<dynamic>? list = widget.menuDataRender!(_currentMenuIndex);
      if (list != null && list.length > 8 && _isShowMask) {
        if (_aliveSearchContent != null) {
          List? result = widget.searchResultCallback!(
              menuIndex, _aliveSearchContent ?? '');
          if (result != null) {
            _aliveSearch[menuIndex] = result;
            renderDropDownWidget();
            setState(() {});
          }
        }
        if (widget.aliveTimeSearch != null) {
          bool? isChanged = widget.aliveTimeSearch?.call(menuIndex);
          if (isChanged == null || isChanged) {
            return renderKqSearchBar(menuIndex, true);
          } else {
            return renderKqSearchBar(menuIndex, false);
          }
        } else {
          return renderKqSearchBar(menuIndex, true);
        }
      }
    }
    return const SizedBox();
  }

  Widget renderKqSearchBar(int menuIndex, bool isChange) {
    if (isChange) {
      return KqSearchBar(
        outerBgColor: KqThemeColors.bgDefault,
        onChanged: (value) {
          if (widget.searchResultCallback != null) {
            List? result = widget.searchResultCallback!(menuIndex, value);
            if (result != null && result.isNotEmpty) {
              // widget.menuData![menuIndex] = result;
              _aliveSearch[menuIndex] = result;
              _aliveSearchContent = value;
            } else {
              _aliveSearch[menuIndex] = [];
              _aliveSearchContent = null;
            }
            renderDropDownWidget();
            setState(() {});
          }
        },
        onCancel: () {
          _aliveSearch.remove(_currentMenuIndex);
          _aliveSearchContent = null;
          if (widget.menuDataRender != null) {
            widget.menuDataRender!(menuIndex);
          }
          renderDropDownWidget();
          setState(() {});
        },
        onSubmit: (p0, state0) {
          if (p0 == '') {
            // _aliveSearch[menuIndex] = [];
            _aliveSearch.remove(_currentMenuIndex);
            _aliveSearchContent = null;
            renderDropDownWidget();
            // if (widget.cancelSearchCallback != null) {
            //   widget.cancelSearchCallback!(menuIndex);
            // }
            // setState(() {});
          } else {
            if (widget.searchResultCallback != null) {
              List? result = widget.searchResultCallback!(menuIndex, p0);
              if (result != null && result.isNotEmpty) {
                // widget.menuData![menuIndex] = result;
                _aliveSearch[menuIndex] = result;
                _aliveSearchContent = p0;
              } else {
                _aliveSearch[menuIndex] = [];
                _aliveSearchContent = null;
              }
              renderDropDownWidget();
              setState(() {});
            }
          }
        },
      );
    } else {
      return KqSearchBar(
        outerBgColor: KqThemeColors.bgDefault,
        onCancel: () {
          _aliveSearch.remove(_currentMenuIndex);
          _aliveSearchContent = null;
          if (widget.menuDataRender != null) {
            widget.menuDataRender!(menuIndex);
          }
          renderDropDownWidget();
          setState(() {});
        },
        onSubmit: (p0, state0) {
          if (p0 == '') {
            // _aliveSearch[menuIndex] = [];
            _aliveSearch.remove(_currentMenuIndex);
            _aliveSearchContent = null;
            renderDropDownWidget();
            // if (widget.cancelSearchCallback != null) {
            //   widget.cancelSearchCallback!(menuIndex);
            // }
            // setState(() {});
          } else {
            if (widget.searchResultCallback != null) {
              List? result = widget.searchResultCallback!(menuIndex, p0);
              if (result != null && result.isNotEmpty) {
                // widget.menuData![menuIndex] = result;
                _aliveSearch[menuIndex] = result;
                _aliveSearchContent = p0;
              } else {
                _aliveSearch[menuIndex] = [];
                _aliveSearchContent = null;
              }
              renderDropDownWidget();
              setState(() {});
            }
          }
        },
      );
    }
  }

  Widget renderLine(int menuIndex) {
    if (widget.menuDataRender != null) {
      List<dynamic>? list = widget.menuDataRender!(_currentMenuIndex);
      if (list != null && list.length > 8 && _isShowMask) {
        return Container(
          color: KqThemeColors.bgDefault,
          child: const KqDivider(),
        );
      }
    }
    return const SizedBox();
  }

  renderbuildConditionListWidget(items) {
    if (widget.menuDataRender != null) {
      List<dynamic>? list = widget.menuDataRender!(_currentMenuIndex);
      List<dynamic>? searchList = _aliveSearch[_currentMenuIndex];
      if (searchList != null) {
        //说明正在搜索
        list = searchList;
      }
      if (list != null && list.isNotEmpty && _isShowMask) {
        return ListView.separated(
          controller: _scrollController,
          shrinkWrap: true,
          padding: EdgeInsets.zero,
          scrollDirection: Axis.vertical,
          // item 的个数
          itemCount: items.length,
          // 添加分割线
          separatorBuilder: (BuildContext context, int index) =>
              const KqDivider(),
          itemBuilder: (BuildContext context, int index) {
            return gestureDetector(items, index);
          },
        );
      }
    }
    //显示暂无数据
    return Container(
      color: KqThemeColors.bgDefault,
      width: double.infinity,
      padding: EdgeInsets.fromLTRB(12.r, 10.r, 0, 0),
      height: _animation == null ? 0 : _animation!.value,
      child: Text(
        KqIntl.currentResource.noDataTip,
        textAlign: TextAlign.start,
        style: TextStyle(
            fontSize: KqThemeManager.getPullDownMenuConfig().menuFontSize,
            color: KqThemeColors.textBlack85),
      ),
    );
  }

  Widget gestureDetector(items, int index) {
    var currentItem = items[index];
    var selectItem = widget.controller.chosenData[widget.controller.menuIndex];
    String titleStr =
        widget.menuItemRender!(widget.controller.menuIndex, currentItem);
    bool isSelcted = widget.isDataSame!(currentItem, selectItem);
    bool isShowSort = false;
    if (widget.isShowSortRender != null) {
      isShowSort = widget.isShowSortRender!(widget.controller.menuIndex);
    }
    return KqInkWell(
      onTap: () {
        widget.controller.isRemoveMenu = true;
        widget.controller.changeChosenData(currentItem);
        widget.controller.hide();
        if (widget.pullDownCallback != null) {
          //回调
          widget.pullDownCallback!(
              currentItem, widget.controller.menuIndex, widget.controller);
        }
      },
      child: SizedBox(
        width: double.infinity,
        height: 64.r,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 24.r,
            ),
            isShowSort
                ? Container(
                    margin: EdgeInsets.fromLTRB(0, 0, 24.r, 0),
                    decoration: BoxDecoration(
                      color: KqThemeColors.bgF0,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Container(
                      alignment: AlignmentDirectional.center,
                      width: 32.r,
                      height: 32.r,
                      child: Text(
                        index.toString(),
                        style: TextStyle(
                            color: KqThemeColors.textBlack85,
                            fontSize: KqThemeManager.getPullDownMenuConfig()
                                .menuFontSize),
                      ),
                    ),
                  )
                : const SizedBox(),
            Expanded(
              child: Text(
                titleStr,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: KqThemeManager.getPullDownMenuConfig().menuFontSize,
                  color: isSelcted
                      ? KqThemeManager.getPullDownMenuConfig().selectColor
                      : KqThemeColors.textBlack85,
                ),
              ),
            ),
            isSelcted
                ? Icon(
                    Icons.check,
                    color: KqThemeManager.getPullDownMenuConfig().selectColor,
                    size: 24.r,
                  )
                : const SizedBox(),
            SizedBox(
              width: 24.r,
            ),
          ],
        ),
      ),
    );
  }
}
